import router from '@/router';
import store from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getPageTitle } from '@/utils/index';
// import { checkRoute } from '@/utils/handleRoutes';
import { setting } from '@/config/setting';
const { loginInterception, progressBar, routesWhiteList, recordRoute } = setting;
import { waterMark } from '@/utils/index';
NProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
});

// 根据权限动态生成路由
const generateDynamicRoutes = async (to, next, permList) => {
  let accessRoutes = [];
  if (store.getters['routes/routes'] && store.getters['routes/routes'].length === 0) {
    accessRoutes = await store.dispatch('routes/setRoutes', permList);
  }

  // 挂载到vue-router实例上
  accessRoutes.forEach((item) => {
    router.addRoute(item);
  });

  store.dispatch('routes/setRouteFlag', true);

  next({ ...to, replace: true });
};

// 不校验权限的路由
const noNeedAuthList = ['/404', '/401', '/'];

// 路由拦截
router.beforeEach(async (to, from, next) => {
  if (progressBar) NProgress.start();

  // 校验token
  let hasToken = store.getters['user/accessToken'];

  if (!loginInterception) hasToken = true;

  if (hasToken) {
    // 已有token，过滤login路由(url中直接输入/login的情况)
    if (to.path === '/login') {
      next({ path: '/' });
      if (progressBar) NProgress.done();
    } else {
      // 无需校验权限的路由，直接跳转
      if (noNeedAuthList.includes(to.path)) {
        next();
      } else {
        const permList = store.getters['user/permList'];
        // 校验目标路由权限
        // const hasPermission = permList.find((item) => item.perms == to.meta.permCode);
        // if (hasPermission) {
        //   next();
        // }

        // 如果动态路由标记为true，则不再动态生成路由
        if (!store.getters['routes/routeFlag']) {
          await generateDynamicRoutes(to, next, permList);
        } else {
          next();
        }
      }
    }
  } else {
    // 免登录路由
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (recordRoute) {
        next(`/login?redirect=${to.path}`);
      } else {
        next('/login');
      }
      if (progressBar) NProgress.done();
    }
  }
  document.title = getPageTitle(to.meta.title);
});

router.afterEach(() => {
  if (progressBar) NProgress.done();
});
